#!/usr/bin/env bash
set -euo pipefail

show_usage() {
  cat <<'USAGE'
Usage:
  ./setup.sh en [files...]   # copy English commands (all when files omitted)
  ./setup.sh cn [files...]   # copy Chinese commands (all when files omitted)

Examples:
  ./setup.sh en
  ./setup.sh en build.md test.md
  ./setup.sh cn cleanup.md troubleshoot.md
USAGE
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  show_usage
  exit 0
fi

ROOT_DIR="$(pwd)"
TARGET_DIR="${ROOT_DIR}/.cursor/commands"
LANG="${1:-en}"
shift || true

case "${LANG}" in
  en|EN) SRC_DIR="${ROOT_DIR}/commands/en" ;;
  cn|CN|zh|ZH) SRC_DIR="${ROOT_DIR}/commands/cn" ;;
  *) echo "[ERROR] Unknown language: ${LANG}. Use en|cn." >&2; exit 1 ;;
esac

mkdir -p "${TARGET_DIR}"

copy_all() {
  shopt -s nullglob
  local files=("${SRC_DIR}"/*.md)
  if (( ${#files[@]} == 0 )); then
    echo "[WARN] No .md files found under ${SRC_DIR}" >&2
    return 0
  fi
  cp -f "${files[@]}" "${TARGET_DIR}/"
}

copy_selected() {
  local missing=0
  for f in "$@"; do
    if [[ -f "${SRC_DIR}/${f}" ]]; then
      cp -f "${SRC_DIR}/${f}" "${TARGET_DIR}/"
    else
      echo "[WARN] Skip missing: ${SRC_DIR}/${f}" >&2
      missing=1
    fi
  done
  return ${missing}
}

if [[ $# -eq 0 ]]; then
  echo "[INFO] Copying ALL from ${SRC_DIR} -> ${TARGET_DIR}"
  copy_all
else
  echo "[INFO] Copying SELECTED from ${SRC_DIR} -> ${TARGET_DIR}: $*"
  copy_selected "$@" || true
fi

echo "[DONE] Commands available under ${TARGET_DIR}"


